package com.zsd.android.dblib;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.text.TextUtils;

import com.zsd.android.dblib.bean.UpdateDb;
import com.zsd.android.dblib.bean.UpdateStep;
import com.zsd.android.dblib.bean.UpdateXml;
import com.zsd.android.dblib.bean.User;
import com.zsd.android.dblib.db.BaseDaoFactory;
import com.zsd.android.dblib.db.UserDao;

import org.w3c.dom.Document;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import javax.xml.parsers.DocumentBuilderFactory;

public class UpdateManager {

    private List<User> userList;

    public void startUpdateDb(Context mContext) {
        UserDao userDao = BaseDaoFactory.getInstance().getBaseDao(UserDao.class, User.class);
        userList = userDao.query(new User());
        //解析xml文件
        UpdateXml updateXml = readDbXml(mContext);
        //拿到当前版本信息
        UpdateStep updateStep = analyseUpdateStep(updateXml);
        if (updateStep == null) {
            return;
        }
        //获取更新用的对象
        List<UpdateDb> updateDbs = updateStep.getUpdateDbs();
        for (User user : userList) {
            //得到每一个用户的数据库对象
            SQLiteDatabase database = getDb(user.getId());
            if (database != null) {
                for (UpdateDb updateDb : updateDbs) {
                    String sqlRename = updateDb.getSqlRename();
                    String sqlCreate = updateDb.getSqlCreate();
                    String sqlInsert = updateDb.getSqlInsert();
                    String sqlDelete = updateDb.getSqlDelete();
                    String[] sqls = new String[]{sqlRename, sqlCreate, sqlInsert, sqlDelete};
                    //执行sql语句
                    executeSql(database, sqls);
                }
            }
        }
    }

    /**
     * 解析xml文件
     * @param mContext
     * @return
     */
    public UpdateXml readDbXml(Context mContext) {
        InputStream is = null;
        Document document = null;
        try {
            is = mContext.getAssets().open("updateXml.xml");
            document = DocumentBuilderFactory.newInstance()
                    .newDocumentBuilder()
                    .parse(is);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (document == null) {
                return null;
            }
        }
        UpdateXml xml = new UpdateXml(document);
        return xml;
    }

    /**
     * 拿到当前版本信息
     * @param updateXml
     * @return
     */
    private UpdateStep analyseUpdateStep(UpdateXml updateXml) {
        UpdateStep thisStep = null;
        if (updateXml == null) {
            return null;
        }
        List<UpdateStep> steps = updateXml.getUpdateSteps();
        if (steps == null || steps.size() == 0) {
            return null;
        }
        for (UpdateStep step : steps) {
            String versionFrom = step.getVersionFrom();
            String versionTo = step.getVersionTo();
            forStep:
            if (TextUtils.isEmpty(versionFrom) || TextUtils.isEmpty(versionTo)) {

            } else {
                String[] versionArray = step.getVersionFrom().split(",");
                if (versionArray != null && versionArray.length > 0) {
                    for (int i = 0; i < versionArray.length; i++) {
                        //V002是当前版本，真是项目要保存在sp中
                        //V003应该从服务器获取
                        if ("V002".equalsIgnoreCase(versionArray[i]) &&
                                step.getVersionTo().equalsIgnoreCase("V003")) {
                            thisStep = step;
                            break forStep;
                        }
                    }
                }
            }
        }
        return thisStep;
    }

    /**
     * 根据用户id获取用户的数据库
     * @param userId
     * @return
     */
    private SQLiteDatabase getDb(int userId) {
        SQLiteDatabase sqlDb = null;
        File file = new File("data/data/com.zsd.android.dblib/u_" + userId + "_private.db");
        if (!file.exists()) {
            return null;
        }
        sqlDb = SQLiteDatabase.openOrCreateDatabase(file, null);
        return sqlDb;
    }

    /**
     * 执行sql语句
     * @param database
     * @param sqls
     */
    private void executeSql(SQLiteDatabase database, String[] sqls) {
        if (sqls == null || sqls.length == 0) {
            return;
        }
        //事务
        database.beginTransaction();
        for (String sql : sqls) {
            sql = sql.replace("\r\n", " ");
            sql = sql.replace("\n", " ");
            if (!"".equals(sql.trim())) {
                database.execSQL(sql);
            }
        }
        database.setTransactionSuccessful();
        database.endTransaction();
    }
}
